package com.sinodoggo.shitcloud.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sinodoggo.shitcloud.commons.Result;
import com.sinodoggo.shitcloud.entity.Avatar;
import com.sinodoggo.shitcloud.entity.Files;
import com.sinodoggo.shitcloud.service.IAvatarService;
import com.sinodoggo.shitcloud.service.IFilesService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sinodoggo
 * @since 2022-11-23
 */
@RestController
@RequestMapping("/avatar")
public class AvatarController {
    private final String serverUrl = "http://localhost:18080/avatar";
    @Value("${avatar.upload.path}")
    private String avatarUploadPath;
    @Resource
    private IAvatarService avatarService;

    @PostMapping("/upload")
    public Result avatarUpload(@RequestParam("file") MultipartFile file) throws IOException {
        // 头像存储在服务器中的URL
        String url;
        // 获取原文件信息
        final String originalFilename = file.getOriginalFilename();
        final String extName = FileUtil.extName(originalFilename);
        final long fileSize = file.getSize();
        // 文件保存在系统中的信息
        final String uuid = IdUtil.fastSimpleUUID();
        String currentFileName = uuid + StrUtil.DOT + extName;
        File uploadFile = new File(avatarUploadPath + currentFileName);
        // 如果父目录不存在，则创建
        if (!uploadFile.getParentFile().exists()) {
            uploadFile.getParentFile().mkdirs();
        }
        // md5校验，避免多次存储浪费磁盘资源（上传记录保留）
        final String md5 = SecureUtil.md5(file.getInputStream());
        QueryWrapper<Avatar> wrapper = new QueryWrapper<>();
        wrapper.eq("md5", md5);
        final List<Avatar> dbRecord = avatarService.list(wrapper);
        if (0 != dbRecord.size()) {
            url = dbRecord.get(0).getUrl();
        } else {
            file.transferTo(uploadFile);
            url = this.serverUrl + "/" + currentFileName;
        }
        // 保存数据库记录
        Avatar saveFile = new Avatar();
        saveFile.setName(originalFilename);
        saveFile.setType(extName);
        saveFile.setSize((double) (fileSize / 1024));
        saveFile.setUrl(url);
        saveFile.setMd5(md5);
        avatarService.save(saveFile);
        return Result.success(url);
    }

    /**
     * 数据库中的URL会映射到此接口
     * @param fileName 头像文件名
     * @param response 辅助响应对象
     * @return 结果集
     */
    @GetMapping("/{fileName}")
    public Result downloadFile(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        File downloadFile = new File(avatarUploadPath + fileName);
        // 文件下载统一设置
        final ServletOutputStream outputStream = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("application/octet-stream");
        outputStream.write(FileUtil.readBytes(downloadFile));
        outputStream.flush();
        outputStream.close();
        return Result.success();
    }
}

